package com.agileai.em.module.evection.handler;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.em.module.evection.service.EmEvectionManage;
import com.agileai.hotweb.controller.core.MasterSubEditPboxHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.StringUtil;

public class EmExpensesEditBoxHandler
        extends MasterSubEditPboxHandler {
    public EmExpensesEditBoxHandler() {
        super();
        this.serviceId = buildServiceId(EmEvectionManage.class);
        this.subTableId = "EmExpenses";
    }
    public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		if(OperaType.CREATE.equals(operaType)){
			setAttribute("EXP_TRANSPORTATION_FEE", "0.00");
			setAttribute("EXP_HOREL_FEE", "0.00");
			setAttribute("EXP_OTHER_FEE", "0.00");
		}
		if (isReqRecordOperaType(operaType)){
			DataRow record = getService().getSubRecord(subTableId, param);
			this.setAttributes(record);			
		}
		String mark = param.getString("mark");
		this.setAttribute("onApproving", false);
		if(StringUtil.isNotNullNotEmpty(mark)){
			this.setAttribute("onApproving", true);
		}
		this.setOperaType(operaType);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}
    
    protected void processPageAttributes(DataParam param) {
        if (!StringUtil.isNullOrEmpty(param.get("EVE_ID"))) {
            this.setAttribute("EVE_ID", param.get("EVE_ID"));
        }
        setAttribute("EXP_TRANSPORTATION_WAY",FormSelectFactory.create("TRANSPORTATION_WAY")
        		.addSelectedValue(getAttributeValue("EXP_TRANSPORTATION_WAY", "")));
    }
    
    public ViewRenderer doSaveAction(DataParam param){
		String responseText = FAIL;
		try {
			String operateType = param.get(OperaType.KEY);
			if(param.get("EXP_TRANSPORTATION_FEE").isEmpty()){
				param.put("EXP_TRANSPORTATION_FEE","0.00");
			}
			if(param.get("EXP_HOREL_FEE").isEmpty()){
				param.put("EXP_HOREL_FEE","0.00");
			}
			if(param.get("EXP_OTHER_FEE").isEmpty()){
				param.put("EXP_OTHER_FEE","0.00");
			}
			if (OperaType.CREATE.equals(operateType)){
				getService().createSubRecord(subTableId, param);
				responseText = SUCCESS;
			}else if (OperaType.UPDATE.equals(operateType)){
				getService().updateSubRecord(subTableId, param);
				responseText = SUCCESS;
			}
			String masterRecordId = param.get("EVE_ID");
			this.getService().computeTotalMoney(masterRecordId);
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(), e);
		}
		return new AjaxRenderer(responseText);
	}
    
    protected EmEvectionManage getService() {
        return (EmEvectionManage) this.lookupService(this.getServiceId());
    }
}
